<template>
  <page-container :title="route.meta.title">
    <SearchTable ref="tableRef" :table-list-api="tableListApi" :columns="columns">
      <template #tableBtns>
        <a-button v-action:create type="primary" @click="handleCreating">新建</a-button>
      </template>
    </SearchTable>
    <DialogViewer v-if="pageType === PAGE_TYPE.VIEW" :form-data="formData" :items="columns" @cancel="handleCancel" />
    <FormDialog
      v-if="pageType === PAGE_TYPE.CREATING || pageType === PAGE_TYPE.EDITING"
      ref="createForm"
      :mode="pageType"
      :form-data="formData"
      :items="columns"
      @ok="handleOk"
      @cancel="handleCancel"
    />
  </page-container>
</template>

<script setup lang="tsx">
import { useRoute } from 'vue-router';
import { Modal } from 'ant-design-vue';
import SearchTable from '@/components/SearchTable';
import useTablePage, { PAGE_TYPE } from '@/hooks/useTablePage';
import { createMedia, modifyMedia, deleteMedia, enableMedia } from '@/api/medium';
import type { IColumn, IRow } from '@/types';

const route = useRoute();
const { pageType, $auth } = useTablePage();
const tableListApi = '/v1/media/list';
const tableRef = ref();

const getActions = () => {
  let actionWidth = 80;
  let record: IRow;

  const btns = [
    <a-button type="link" onClick={() => handleGeting(record)}>
      查看
    </a-button>,
  ];

  if ($auth('edit')) {
    actionWidth += 60;
    btns.push(
      <a-button type="link" onClick={() => handleEditing(record)}>
        编辑
      </a-button>,
    );
  }

  if ($auth('delete')) {
    actionWidth += 60;
    btns.push(
      <a-button type="link" danger onClick={() => handleDeleting(record)}>
        删除
      </a-button>,
    );
  }

  const setRecord = (_record: IRow) => (record = _record);

  return { btns, actionWidth, setRecord };
};

const { btns, actionWidth, setRecord } = getActions();

const columns: IColumn[] = [
  {
    title: '媒体账号',
    dataIndex: 'id',
    readonly: true,
  },
  {
    title: '媒体名称',
    dataIndex: 'name',
    searchable: true,
  },
  {
    title: 'secretKey',
    dataIndex: 'secretKey',
    readonly: true,
  },
  {
    title: '状态',
    type: 'boolean',
    dataIndex: 'status',
    switchLabels: ['启用', '禁用'],
    readonly: true,
    customRender({ text, record }) {
      return (
        <a-switch
          checked={text}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          onClick={(enable: boolean) => handleEnable(record.id, enable)}
        />
      );
    },
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    width: actionWidth,
    fixed: 'right',
    customRender: ({ record }) => {
      setRecord(record);
      return btns;
    },
  },
];

const formData = ref({});
const handleGeting = (record: IRow) => {
  formData.value = record;
  pageType.value = PAGE_TYPE.VIEW;
};
const handleCreating = () => {
  formData.value = {};
  pageType.value = PAGE_TYPE.CREATING;
};

const handleEditing = (record: Record<string, unknown>) => {
  console.log('🚀 ~ handleEditing ~ record:', record);
  formData.value = record;
  pageType.value = PAGE_TYPE.EDITING;
};

const handleDeleting = (record: IRow) => {
  Modal.confirm({
    title: '警告',
    content: `确认删除 ${record.name} 吗?`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return deleteMedia(record.id).then(() => {
        tableRef.value.refreshTable();
      });
    },
  });
};

const handleOk = async (state: any) => {
  if (pageType.value === PAGE_TYPE.CREATING) {
    await createMedia(state);
  } else {
    await modifyMedia(state);
  }
  pageType.value = null;
  tableRef.value.refreshTable();
};

const handleCancel = () => {
  pageType.value = null;
};
const handleEnable = (id: string, enable: boolean) => {
  Modal.confirm({
    title: '警告',
    content: `确认是否${enable ? '启用' : '禁用'}该媒体方？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return enableMedia(id).then(() => {
        tableRef.value.refreshTable();
      });
    },
  });
};
</script>
